package com.solarStruggle.controls

import java.awt.{Color, Graphics, Image}
import javax.swing.{ImageIcon, JToolBar}

import scala.swing.{Button, Component, Label, Panel, ScrollPane}
import scala.swing.event.{ComponentResized, MouseClicked}
import actions.{ZoomInAction, ZoomOutAction, ZoomResetAction}
import domain.{SolarSystem}
import graphics.{BufferedImage, ProceduralImageGenerator, LayeredImageGenerator}
import util.{ResourceLoader}

class BattleField(state: GuiState) 
extends MigPanel("", "[100%]", "[100%]") {

  val introImage = new ImageIcon(ResourceLoader.getResourceURL("img/intro.png")).getImage;
  
  val fieldLabel = new Label()
  
  val scroller = new ScrollPane {
    contents = fieldLabel
  }
  add(scroller, "growx, growy")
  
  state.reactions += {
    case ZoomLevelChanged(_) => updateImage()
    case CurrentSolarSystemChanged(_) => updateImage()
  }
  
  state.zoomLevel = state.resetZoomLevel
  
  reactions += {
    case ComponentResized(_) => updateImage()
  }
  
  def updateImage() {
    if(state.currentSolarSystem.isEmpty || state.currentGame.isEmpty) {
      fieldLabel.icon = new ImageIcon(getIntroImage());
    } else {
      fieldLabel.icon = new ImageIcon(getSolarSystemImage());
    }
  }
  
  def getIntroImage(): Image = {
    val introScaleBy: Double = if(size.width > 0 && size.height > 0) {
      Math.min(
        size.width.toDouble / introImage.getWidth(null).toDouble, 
        size.height.toDouble / introImage.getHeight(null)).toDouble
    } else {
      1.0d
    }
    
    val newImage = new BufferedImage(
      (introImage.getWidth(null) * introScaleBy).toInt, 
      (introImage.getHeight(null) * introScaleBy).toInt);
    newImage.getGraphics.drawImage(introImage, 0, 0, newImage.getWidth, newImage.getHeight, null);
    newImage;
  }
  
  def getSolarSystemImage(): Image = {
    val game = state.currentGame.get
    val scaleBy = state.zoomFactor
    val ssImage = state.currentSolarSystem.get.image
    val zoomedImage = new BufferedImage(
      (introImage.getWidth(null) * scaleBy).toInt, 
      (introImage.getHeight(null) * scaleBy).toInt)
    val squareSize = (64 * scaleBy).toInt
    zoomedImage.getGraphics.drawImage(ssImage, 0, 0, zoomedImage.getWidth, zoomedImage.getHeight, null)

    val grid = new ProceduralImageGenerator(zoomedImage.getWidth, zoomedImage.getHeight, new Color(0, 0, 0, 0), squareSize) {
      override def renderPixel(image: BufferedImage, x: Int, y: Int) {
        val g = image.getGraphics
        g.setColor(new Color(192, 192, 192, 64))
        g.drawLine(x, y, x + squareSize, y)
        g.drawLine(x, y, x, y + squareSize)
    } }.createImage
    new LayeredImageGenerator(zoomedImage :: grid :: Nil).createImage
  }
}
